<template>
  <el-row>
    <el-col :span="12">
      <div style="margin-right: 0" class="app-container">
        <el-row style="border-bottom: 1px solid rgb(223, 230, 236); margin-bottom: 20px">
          <el-col :span="6">
            <h2 style="font-size: 20px; font-weight: bold; margin-top: 4px">用户组管理</h2>
          </el-col>
          <el-col :span="18">
            <el-form style="text-align: right" :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
              <el-form-item label="用户组名称" prop="userGroupName">
                <el-input
                  v-model="queryParams.userGroupName"
                  placeholder="请输入用户组名称"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['userGroup:group:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['userGroup:group:edit']"
            >
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="single"
              @click="handleDelete"
              v-hasPermi="['userGroup:group:remove']"
            >
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-setting"
              size="mini"
              :disabled="single"
              @click="handleControlSetting"
              v-hasPermi="['userGroup:group:control']"
            >
              权限配置
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              plain
              type="success"
              icon="el-icon-plus"
              size="mini"
              :disabled="single"
              @click="handleOpenUser"
              v-hasPermi="['userGroup:group:addUser']"
            >
              添加已有用户
            </el-button>
          </el-col>
		  <el-col :span="1.5">
		    <el-button
		      plain
		      type="primary"
		      icon="el-icon-plus"
		      size="mini"
		      :disabled="single"
		      @click="handleJurisdiction"
		      v-hasPermi="['userGroup:group:Jurisdiction']"
		    >
		      应用权限
		    </el-button>
		  </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="tableList"
          row-key="userGroupId"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="用户组名称" prop="userGroupName" />
          <el-table-column label="用户组说明" prop="instructions" :show-overflow-tooltip="true" />
          <el-table-column label="状态" align="center" width="120">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加或修改角色配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="120px" style="margin-right: 30px">
            <el-form-item label="用户组名称" prop="userGroupName">
              <el-input v-model="form.userGroupName" placeholder="请输入用户组名称" />
            </el-form-item>
            <el-form-item label="上级用户组" prop="parentId">
              <treeselect
                v-model="form.parentId"
                :options="groupTree"
                :show-count="true"
                placeholder="请选择上级用户组"
              />
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">{{
                  dict.dictLabel
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="用户组说明" prop="instructions">
              <el-input v-model="form.instructions" type="textarea" placeholder="请输入用户组说明" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
        <!-- 权限对话框 -->
        <el-dialog title="权限配置" :visible.sync="control.open" width="500px" append-to-body>
          <el-form style="margin-top: -20px" ref="controlForm" :model="controlForm" label-width="80px">
            <el-form-item label="菜单权限">
              <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
              <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
              <el-checkbox v-model="controlForm.menuCheckStrictly" @change="handleCheckedTreeConnect($event)"
                >父子联动</el-checkbox
              >
              <el-tree
                class="tree-border"
                :data="menuOptions"
                show-checkbox
                ref="menu"
                node-key="id"
                :check-strictly="!controlForm.menuCheckStrictly"
                empty-text="加载中，请稍后"
                :props="defaultProps"
              ></el-tree>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitControlForm">确 定</el-button>
            <el-button @click="cancelControl">取 消</el-button>
          </div>
        </el-dialog>

		<!-- 应用权限 -->
		<el-dialog title="角色权限配置" :visible.sync="Jurisdiction" width="600px" append-to-body>
		  <el-form style="margin-top: -20px" ref="controlForm2" :model="controlForm2" label-width="80px">
		    <el-form-item label="所拥有的权限">
		      <el-tree
		        class="tree-border"
		        :data="Jurisdiction_list"
		        show-checkbox
		        ref="menu2"
		        node-key="receptionApplyId"
		        :check-strictly="!controlForm2.menuCheckStrictly"
		        empty-text="加载中，请稍后"
		        :props="defaultProps2"
		      ></el-tree>
		    </el-form-item>
		  </el-form>
		  <div slot="footer" class="dialog-footer">
		    <el-button type="primary" @click="submitControlForm1">确 定</el-button>
		    <el-button @click="cancelControl1">取 消</el-button>
		  </div>
		</el-dialog>
        <!-- 添加已有用户对话框 -->
        <user-dialog :groupId="ids" ref="userDialog" @ok="successAddUser" />
      </div>
    </el-col>
    <el-col :span="12">
      <div class="app-container">
        <el-row style="border-bottom: 1px solid rgb(223, 230, 236); margin-bottom: 20px">
          <el-col :span="3">
            <h2 style="font-size: 20px; font-weight: bold; margin-top: 4px">在组用户</h2>
          </el-col>
          <el-col v-show="!single" :span="21">
            <el-form
              style="text-align: right"
              :model="userQueryParams"
              ref="userQueryForm"
              v-show="userShowSearch"
              :inline="true"
            >
              <el-form-item label="学号/工号" prop="userId">
                <el-input
                  style="width: 160px"
                  v-model="userQueryParams.userId"
                  placeholder="请输入学号/工号"
                  clearable
                  size="small"
                  @keyup.enter.native="handleUserQuery"
                />
              </el-form-item>
              <el-form-item label="姓名" prop="nickName">
                <el-input
                  style="width: 160px"
                  v-model="userQueryParams.nickName"
                  placeholder="请输入姓名"
                  clearable
                  size="small"
                  @keyup.enter.native="handleUserQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetUserQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>

        <el-row v-show="!single" :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleImport(1)"
              v-hasPermi="['userGroup:user:import']"
              >批量导入</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="handleImport(0)"
              v-hasPermi="['userGroup:user:export']"
            >
              批量移除
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="userShowSearch" @queryTable="getUserList"></right-toolbar>
        </el-row>

        <el-table
          v-loading="userLoading"
          :data="userTableList"
          row-key="userId"
          @selection-change="handleSelectionChange"
        >
          <el-table-column label="工号/学号" prop="userId" />
          <el-table-column label="姓名" prop="nickName" />
          <el-table-column label="角色" align="center">
            <template slot-scope="scope">
              <span>{{ (scope.row.sysRoleList || []).map(item => item.roleName).join(', ') }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="userTotal > 0"
          :total="userTotal"
          :page.sync="userQueryParams.pageNum"
          :limit.sync="userQueryParams.pageSize"
          @pagination="getUserList"
        />

        <!-- 批量新增/删除 对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
          <el-upload
            ref="upload"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            :data="upload.data"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <!--<div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" />
              是否更新已经存在的用户数据
            </div>-->
            <div class="el-upload__tip" slot="tip">
              <el-link icon="el-icon-download" type="info" style="font-size: 14px" @click="handleDownloadTemplate"
                >下载模板</el-link
              >
            </div>
            <div class="el-upload__tip" style="color: red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </el-col>
  </el-row>
</template>

<script>
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import userDialog from './userDialog'
  import { treeselect as menuTreeselect } from '@/api/system/menu'
  import {
    listUserGroup,
    treeUserGroup,
    addUserGroup,
    delGroup,
    getUserGroup,
    updateGroupControl,
    updateUserGroup,
    updateGroupApply,
	jurisdiction
  } from './service'
  import { listUserInGroup } from '@/pages/views/userGroup/groupManage/service'
  import { getToken } from '@/utils/auth'
  import { importTemplate } from '@/pages/views/account/manage/service'

  export default {
    name: 'GroupManage',
    components: { Treeselect, userDialog },
    data() {
      return {
        // 遮罩层
        loading: true,
        userLoading: false,
        // 选中数组
        ids: [],
        selectedRows: [],
		selectedRows2:[],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        userShowSearch: true,
        // 总条数
        total: 0,
        userTotal: 0,
        // 角色表格数据
        tableList: [],
        userTableList: [],
        groupTree: [],
        // 弹出层标题
        title: '',
        userTitle: '',
        // 是否显示弹出层
        open: false,
        userOpen: false,
        control: {
          open: false
        },
		/* 应用权限 */
		Jurisdiction:false,
		Jurisdiction_list:[],
        menuExpand: false,
        menuNodeAll: false,
        // 状态数据字典
        statusOptions: [],
        // 菜单列表
        menuOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          userGroupName: undefined
        },
        userQueryParams: {
          pageNum: 1,
          pageSize: 10,
          userGroupName: undefined
        },
        // 表单参数
        form: {
          status: '0'
        },
        controlForm: {
          menuCheckStrictly: true
        },
		controlForm2: {
		  menuCheckStrictly: true
		},
        defaultProps: {
          children: 'children',
          label: 'label'
        },
		defaultProps2: {
		  children: 'children',
		  label: 'menuName'
		},
        // 表单校验
        rules: {
          userGroupName: [{ required: true, message: '用户组名称不能为空', trigger: 'blur' }],
          parentId: [{ required: true, message: '上级用户组不能为空', trigger: 'blur' }]
        },
        // 批量新增/删除 导入参数
        upload: {
          // 是否显示弹出层（导入）
          open: false,
          // 弹出层标题（导入）
          title: '',
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: { Authorization: 'Bearer ' + getToken() },
          // 上传的地址
          url: '',
          data: {},
          updateSupport: false
        }
      }
    },
    watch: {
      ids(newVal) {
        if (newVal && newVal.length === 1) {
          this.getUserList()
        } else {
          this.userTableList = []
          this.userTotal = 0
        }
      }
    },
    created() {
      this.getList()
      this.getGroupTree()
      this.getMenuTreeselect()
      this.getDicts('sys_normal_disable').then(response => {
        this.statusOptions = response.data
      })
    },
    methods: {
      /** 查询列表 */
      getList() {
        this.loading = true
        listUserGroup(this.queryParams)
          .then(response => {
            if (response.code === 200) {
              this.tableList = this.handleTree(response.data, 'userGroupId')
              console.log(this.tableList)
            }
          })
          .finally(() => {
            this.loading = false
          })
      },
      getUserList() {
        this.userLoading = true
        listUserInGroup({ ...this.userQueryParams, groupId: this.ids[0] })
          .then(response => {
            if (response.code === 200) {
              this.userTableList = response.rows
              this.userTotal = response.total
            }
          })
          .finally(() => {
            this.userLoading = false
          })
      },
      getGroupTree() {
        treeUserGroup().then(response => {
          if (response.code === 200) {
            this.groupTree = [{ label: '顶级', id: 0, children: response.data || [] }]
          }
        })
      },
      /** 查询菜单树结构 */
      getMenuTreeselect() {
        menuTreeselect().then(response => {
          this.menuOptions = response.data
        })
      },
      // 所有菜单节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getCheckedKeys()
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
		console.log(checkedKeys)
        return checkedKeys
      },
	  // 所有菜单节点数据
	  getMenuAllCheckedKeys2() {
	    // 目前被选中的菜单节点
	    let checkedKeys = this.$refs.menu2.getCheckedKeys()
	    // 半选中的菜单节点
	    let halfCheckedKeys = this.$refs.menu2.getHalfCheckedKeys()
	    checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
	  		console.log(checkedKeys)
	    return checkedKeys
	  },
      // 状态修改
      handleStatusChange(row) {
        let text = row.status === '0' ? '启用' : '冻结'
        this.$confirm('确定' + text + '当前用户组吗?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(function() {
            return updateUserGroup(row)
          })
          .then(res => {
            console.log(res)
            this.msgSuccess(text + '成功')
          })
          .catch(function() {
            row.status = row.status === '0' ? '1' : '0'
          })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 取消按钮（权限）
      cancelControl() {
        this.control.open = false
        this.resetControl()
      },
	  // 用户权限取消按钮
	  cancelControl1() {
	    this.Jurisdiction = false
	    this.resetControl()
	  },
	   // 用户权限确认按钮
	  submitControlForm1: function() {
		this.controlForm2 = { ...this.selectedRows[0] }
		this.controlForm2.applyIds = this.getMenuAllCheckedKeys2()
		this.$refs['controlForm2'].validate(valid => {
		  if (valid) {
		    updateGroupApply(this.controlForm2).then(response => {
		      this.msgSuccess('权限配置成功')
		      this.Jurisdiction= false
		    })
		  }
		})
	  },
      // 表单重置
      reset() {
        this.form = {
          userGroupId: undefined,
          userGroupName: undefined,
          status: '0',
          instructions: undefined
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      /** 搜索按钮操作 */
      handleUserQuery() {
        this.userQueryParams.pageNum = 1
        if (!this.userQueryParams.userId || /^\d+$/.test(this.userQueryParams.userId)) {
          this.getUserList()
        } else {
          this.userTableList = []
          this.userTotal = 0
        }
      },
      /** 重置按钮操作 */
      resetUserQuery() {
        this.resetForm('userQueryForm')
        this.handleUserQuery()
      },
      // 表单重置
      resetControl() {
        this.controlForm = {
          menuCheckStrictly: true
        }
        this.resetForm('controlForm')
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.userGroupId)
        this.selectedRows = selection
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      // 树权限（展开/折叠）
      handleCheckedTreeExpand(value) {
        let treeList = this.menuOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
        }
      },
      // 树权限（全选/全不选）
      handleCheckedTreeNodeAll(value) {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
      },
      // 树权限（父子联动）
      handleCheckedTreeConnect(value) {
        this.controlForm.menuCheckStrictly = value ? true : false
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '添加用户组'
      },
      /** 修改按钮操作 */
      handleUpdate() {
        this.reset()
        getUserGroup(this.ids).then(res => {
          if (res.code === 200) {
            this.form = res.data
            this.open = true
            this.title = '修改用户组'
          }
        })
      },
      /* 添加已有用户 按钮操作 */
      handleOpenUser() {
        this.$nextTick(function() {
          this.$refs.userDialog.show()
        })
      },
      /** 权限配置 按钮操作 */
      handleControlSetting() {
        this.resetControl()
        getUserGroup(this.ids).then(res => {
          if (res.code === 200) {
            this.controlForm = { ...this.controlForm, ...res.data }
			console.log(this.controlForm)
            this.control.open = true
            const checkedKeys = res.data.menuIds || []
            checkedKeys.forEach(v => {
              this.$nextTick(() => {
                this.$refs.menu.setChecked(v, true, false)
              })
            })
          }
        })
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.userGroupId != undefined) {
              updateUserGroup(this.form).then(response => {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
                this.getGroupTree()
              })
            } else {
              addUserGroup(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('新增成功')
                  this.open = false
                  this.getList()
                  this.getGroupTree()
                }
              })
            }
          }
        })
      },
      /** 提交按钮: 权限配置 */
      submitControlForm: function() {
        this.controlForm = { ...this.selectedRows[0] }
        this.controlForm.menuIds = this.getMenuAllCheckedKeys()
        this.$refs['controlForm'].validate(valid => {
          if (valid) {
            updateGroupControl(this.controlForm).then(response => {
              this.msgSuccess('权限配置成功')
              this.control.open = false
            })
          }
        })
      },
      /* 成功callback: 添加已有用户 */
      successAddUser() {
        this.getUserList()
      },
      /** 删除按钮操作 */
      handleDelete() {
        const groupId = this.ids
        this.$confirm('是否确认删除当前用户组?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(function() {
            return delGroup(groupId)
          })
          .then(res => {
            this.getList()
            this.getGroupTree()
            this.msgSuccess('删除成功')
          })
      },
	  /* 应用权限*/
	  handleJurisdiction(){
		 //  this.reset()
		 // jurisdiction(this.controlForm).then(res=>{
			//  console.log(res)
		 // })
		 console.log(this.controlForm)
		 //this.resetControl()

		 jurisdiction(this.ids).then(res => {
		   if (res.code === 200) {
		     //this.controlForm = { ...this.controlForm, ...res.data }
			 this.Jurisdiction_list=res.data
		     this.Jurisdiction = true
		     const checkedKeys = res.data.menuIds || []
		     checkedKeys.forEach(v => {
		       this.$nextTick(() => {
		         this.$refs.menu.setChecked(v, true, false)
		       })
		     })
		   }
		 })
	  },
      /** 下载模板操作 */
      handleDownloadTemplate() {
        importTemplate().then(response => {
          this.download(response.msg)
        })
      },
      /** 导入按钮操作 */
      handleImport(isAdd) {
        this.upload.url = isAdd
          ? process.env.VUE_APP_BASE_API + '/system/group/importData'
          : process.env.VUE_APP_BASE_API + '/system/group/importDeleteData'
        this.upload.title = isAdd ? '批量新增' : '批量删除'
        this.upload.data = { groupId: this.ids[0] }
        this.upload.open = true
      },
      submitFileForm() {
        this.$refs.upload.submit()
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false
        this.upload.isUploading = false
        this.$refs.upload.clearFiles()
        this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
        this.getUserList()
      }
    }
  }
</script>
